import React, { useState, useRef } from 'react'
// 🔧 修改：使用真实的 API，而不是 mockApi
import { searchDataImages, getDataImages } from '../../utils/api'

export default function SearchModule({ onBack, stats }) {
  const [searchMode, setSearchMode] = useState('text') // 'text', 'similarity', 'advanced'
  const [searchQuery, setSearchQuery] = useState('')
  const [selectedTags, setSelectedTags] = useState([])
  const [dateRange, setDateRange] = useState('all')
  const [sortBy, setSortBy] = useState('createdAt')
  const [viewMode, setViewMode] = useState('grid') // 'grid', 'list'
  
  const [searching, setSearching] = useState(false)
  const [results, setResults] = useState([])
  const [similarityImage, setSimilarityImage] = useState(null)
  const [selectedImage, setSelectedImage] = useState(null)
  
  const fileInputRef = useRef(null)

  // 文本搜索
  async function handleTextSearch() {
    if (!searchQuery.trim() && selectedTags.length === 0) {
      alert('请输入搜索关键词或选择标签')
      return
    }

    setSearching(true)
    try {
      // 🔧 修改：使用新的搜索 API
      const data = await searchDataImages({
        query: searchQuery,
        tags: selectedTags,
        dateRange: dateRange,
        sortBy: sortBy
      })
      setResults(data)
    } catch (err) {
      console.error('搜索失败:', err)
      alert('搜索失败: ' + err.message)
    } finally {
      setSearching(false)
    }
  }

  // 相似图片搜索
  async function handleSimilaritySearch() {
    if (!similarityImage) {
      alert('请先上传参考图片')
      return
    }

    setSearching(true)
    try {
      // 🔧 修改：相似图片搜索需要实现图片ID匹配
      // 暂时显示提示信息
      alert('相似图片搜索功能需要先上传参考图片到系统中')
      setResults([])
    } catch (err) {
      console.error('相似性搜索失败:', err)
      alert('相似性搜索失败: ' + err.message)
    } finally {
      setSearching(false)
    }
  }

  // 加载所有图片
  async function handleLoadAll() {
    setSearching(true)
    try {
      // 🔧 修改：使用新的 API
      const data = await getDataImages()
      setResults(data)
    } catch (err) {
      console.error('加载失败:', err)
      alert('加载失败: ' + err.message)
    } finally {
      setSearching(false)
    }
  }

  // 上传相似图片
  function handleSimilarityImageUpload(e) {
    const file = e.target.files?.[0]
    if (!file) return

    const reader = new FileReader()
    reader.onload = () => {
      setSimilarityImage({
        name: file.name,
        dataUrl: reader.result
      })
    }
    reader.readAsDataURL(file)
    e.target.value = ''
  }

  // 切换标签选择
  function toggleTag(tag) {
    setSelectedTags(prev => 
      prev.includes(tag) 
        ? prev.filter(t => t !== tag)
        : [...prev, tag]
    )
  }

  // 查看图片详情
  function viewImageDetail(image) {
    setSelectedImage(image)
  }

  // 关闭详情模态框
  function closeDetail() {
    setSelectedImage(null)
  }

  // 获取所有可用标签
  const availableTags = Object.keys(stats.tags || {})

  return (
    <div className="search-module">
      {/* 页面标题 */}
      <div className="card">
        <div className="card-header">
          <div className="section-title">
            <span className="section-icon">🔍</span>
            <div>
              <h3 className="card-title">智能搜索</h3>
              <p className="card-subtitle">支持文本搜索、图片相似性搜索和高级筛选</p>
            </div>
          </div>
          <button className="back-btn" onClick={onBack}>
            ← 返回
          </button>
        </div>

        {/* 搜索模式切换 */}
        <div className="search-mode-toggle">
          <button
            className={`mode-btn ${searchMode === 'text' ? 'active' : ''}`}
            onClick={() => setSearchMode('text')}
          >
            <span className="mode-icon">📝</span>
            <span>文本搜索</span>
          </button>
          <button
            className={`mode-btn ${searchMode === 'similarity' ? 'active' : ''}`}
            onClick={() => setSearchMode('similarity')}
          >
            <span className="mode-icon">🖼️</span>
            <span>相似图片</span>
          </button>
          <button
            className={`mode-btn ${searchMode === 'advanced' ? 'active' : ''}`}
            onClick={() => setSearchMode('advanced')}
          >
            <span className="mode-icon">⚙️</span>
            <span>高级搜索</span>
          </button>
        </div>

        {/* 文本搜索 */}
        {searchMode === 'text' && (
          <div className="search-section">
            <div className="search-box-container">
              <input
                type="text"
                className="search-input-large"
                placeholder="输入关键词搜索图片名称、标签或描述..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                onKeyPress={(e) => e.key === 'Enter' && handleTextSearch()}
              />
              <button
                className="search-btn"
                onClick={handleTextSearch}
                disabled={searching}
              >
                {searching ? '搜索中...' : '搜索'}
              </button>
            </div>
          </div>
        )}

        {/* 相似图片搜索 */}
        {searchMode === 'similarity' && (
          <div className="search-section">
            <div className="similarity-search-container">
              <input
                ref={fileInputRef}
                type="file"
                accept="image/*"
                style={{ display: 'none' }}
                onChange={handleSimilarityImageUpload}
              />
              
              {!similarityImage ? (
                <button
                  className="similarity-upload-btn"
                  onClick={() => fileInputRef.current?.click()}
                >
                  <span style={{ fontSize: '24px' }}>📤</span>
                  <span>上传参考图片</span>
                </button>
              ) : (
                <div className="similarity-preview">
                  <img src={similarityImage.dataUrl} alt={similarityImage.name} />
                  <button
                    className="clear-btn"
                    onClick={() => setSimilarityImage(null)}
                  >
                    ✕
                  </button>
                </div>
              )}
              
              <button
                className="search-btn"
                onClick={handleSimilaritySearch}
                disabled={searching || !similarityImage}
                style={{ width: '100%', marginTop: '16px' }}
              >
                {searching ? '搜索中...' : '搜索相似图片'}
              </button>
              
              <p className="similarity-hint">
                上传一张叶片图片，系统将在数据库中查找相似的图片
              </p>
            </div>
          </div>
        )}

        {/* 高级搜索 */}
        {searchMode === 'advanced' && (
          <div className="search-section">
            <div className="search-box-container" style={{ marginBottom: '24px' }}>
              <input
                type="text"
                className="search-input-large"
                placeholder="输入关键词..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
              />
            </div>

            <div className="filter-controls">
              {/* 标签筛选 */}
              <div className="filter-group">
                <div className="filter-label">
                  <span className="label-icon">🏷️</span>
                  <span>缺陷类型</span>
                </div>
                <div className="tag-filters">
                  {availableTags.length > 0 ? (
                    availableTags.map(tag => (
                      <button
                        key={tag}
                        className={`tag-filter ${selectedTags.includes(tag) ? 'active' : ''}`}
                        onClick={() => toggleTag(tag)}
                      >
                        {tag}
                        <span className="tag-count">{stats.tags[tag]}</span>
                      </button>
                    ))
                  ) : (
                    <span style={{ color: '#9ca3af', fontSize: '14px' }}>暂无标签</span>
                  )}
                </div>
              </div>

              {/* 时间筛选 */}
              <div className="filter-group">
                <div className="filter-label">
                  <span className="label-icon">📅</span>
                  <span>时间范围</span>
                </div>
                <div className="date-filters">
                  {[
                    { value: 'all', label: '全部' },
                    { value: 'today', label: '今天' },
                    { value: 'week', label: '本周' },
                    { value: 'month', label: '本月' }
                  ].map(option => (
                    <button
                      key={option.value}
                      className={`date-filter ${dateRange === option.value ? 'active' : ''}`}
                      onClick={() => setDateRange(option.value)}
                    >
                      {option.label}
                    </button>
                  ))}
                </div>
              </div>

              {/* 排序方式 */}
              <div className="filter-group">
                <div className="filter-label">
                  <span className="label-icon">🔄</span>
                  <span>排序</span>
                </div>
                <select
                  className="sort-select"
                  value={sortBy}
                  onChange={(e) => setSortBy(e.target.value)}
                >
                  <option value="createdAt">按时间</option>
                  <option value="name">按名称</option>
                </select>
              </div>
            </div>

            <div style={{ display: 'flex', gap: '12px', marginTop: '24px' }}>
              <button
                className="search-btn"
                onClick={handleTextSearch}
                disabled={searching}
                style={{ flex: 1 }}
              >
                {searching ? '搜索中...' : '开始搜索'}
              </button>
              <button
                className="btn-secondary"
                onClick={() => {
                  setSearchQuery('')
                  setSelectedTags([])
                  setDateRange('all')
                  setSortBy('createdAt')
                }}
              >
                重置筛选
              </button>
            </div>
          </div>
        )}
      </div>

      {/* 视图控制和结果 */}
      {results.length > 0 && (
        <div className="card">
          <div className="results-header">
            <h3 className="results-title">
              <span>🔍</span>
              <span>搜索结果</span>
              <span className="results-count">{results.length} 张</span>
            </h3>
            <div className="view-controls">
              <div className="view-toggle">
                <button
                  className={`view-btn ${viewMode === 'grid' ? 'active' : ''}`}
                  onClick={() => setViewMode('grid')}
                >
                  <span>⊞</span>
                  <span className="view-label">网格</span>
                </button>
                <button
                  className={`view-btn ${viewMode === 'list' ? 'active' : ''}`}
                  onClick={() => setViewMode('list')}
                >
                  <span>☰</span>
                  <span className="view-label">列表</span>
                </button>
              </div>
            </div>
          </div>

          {/* 网格视图 */}
          {viewMode === 'grid' && (
            <div className="image-grid">
              {results.map((img) => (
                <div
                  key={img.id}
                  className="result-image-card"
                  onClick={() => viewImageDetail(img)}
                >
                  <div className="result-image-preview">
                    <img src={img.filepath ? `http://localhost:3000${img.filepath}` : (img.dataUrl || img.url)} alt={img.name} />
                  </div>
                  <div className="result-image-info">
                    <h4 className="result-image-name">{img.name}</h4>
                    {img.tags && img.tags.length > 0 && (
                      <div className="result-image-tags">
                        {img.tags.slice(0, 3).map((tag, idx) => (
                          <span key={idx} className="result-tag">{tag}</span>
                        ))}
                        {img.tags.length > 3 && (
                          <span className="result-tag">+{img.tags.length - 3}</span>
                        )}
                      </div>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* 列表视图 */}
          {viewMode === 'list' && (
            <div className="image-list">
              {results.map((img) => (
                <div
                  key={img.id}
                  className="result-image-list-item"
                  onClick={() => viewImageDetail(img)}
                >
                  <div className="list-item-image">
                    <img src={img.filepath ? `http://localhost:3000${img.filepath}` : (img.dataUrl || img.url)} alt={img.name} />
                  </div>
                  <div className="list-item-content">
                    <h4 className="list-item-name">{img.name}</h4>
                    {img.description && (
                      <p className="list-item-description">{img.description}</p>
                    )}
                    {img.tags && img.tags.length > 0 && (
                      <div className="list-item-tags">
                        {img.tags.map((tag, idx) => (
                          <span key={idx} className="result-tag">{tag}</span>
                        ))}
                      </div>
                    )}
                  </div>
                  <div className="list-item-meta">
                    {img.createdAt && (
                      <span className="meta-date">
                        {new Date(img.createdAt).toLocaleDateString()}
                      </span>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* 空状态 */}
      {!searching && results.length === 0 && (
        <div className="empty-state">
          <div className="empty-icon">🔍</div>
          <h3>开始搜索</h3>
          <p>选择搜索模式，输入关键词或上传图片开始搜索</p>
          <button className="quick-load-btn" onClick={handleLoadAll}>
            <span>📁</span>
            <span>加载所有图片</span>
          </button>
        </div>
      )}

      {/* 加载状态 */}
      {searching && (
        <div className="loading-overlay">
          <div className="loading-spinner"></div>
          <p style={{ marginTop: '16px', color: '#6b7280' }}>搜索中...</p>
        </div>
      )}

      {/* 图片详情模态框 */}
      {selectedImage && (
        <div className="modal-backdrop" onClick={closeDetail}>
          <div className="modal-content" onClick={(e) => e.stopPropagation()}>
            <div className="modal-header">
              <h3>{selectedImage.name}</h3>
              <button className="modal-close-btn" onClick={closeDetail}>✕</button>
            </div>
            <div className="modal-body">
              <div className="modal-image">
                <img src={selectedImage.filepath ? `http://localhost:3000${selectedImage.filepath}` : (selectedImage.dataUrl || selectedImage.url)} alt={selectedImage.name} />
              </div>
              <div className="modal-info">
                {selectedImage.description && (
                  <div className="modal-section">
                    <h4>描述</h4>
                    <p>{selectedImage.description}</p>
                  </div>
                )}
                {selectedImage.tags && selectedImage.tags.length > 0 && (
                  <div className="modal-section">
                    <h4>标签</h4>
                    <div className="modal-tags">
                      {selectedImage.tags.map((tag, idx) => (
                        <span key={idx} className="modal-tag">{tag}</span>
                      ))}
                    </div>
                  </div>
                )}
                {selectedImage.detections && selectedImage.detections.length > 0 && (
                  <div className="modal-section">
                    <h4>检测结果</h4>
                    <div className="detection-list">
                      {selectedImage.detections.map((det, idx) => (
                        <div key={idx} className="detection-item">
                          <span>{det.class || det.label}</span>
                          <span className="detection-confidence">
                            {((det.confidence || 0) * 100).toFixed(1)}%
                          </span>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
                {selectedImage.createdAt && (
                  <div className="modal-section">
                    <h4>创建时间</h4>
                    <p>{new Date(selectedImage.createdAt).toLocaleString()}</p>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
